package com.chatplus.application.controller.api;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.common.exception.BadRequestException;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.dao.file.FileDao;
import com.chatplus.application.domain.entity.file.FileEntity;
import com.chatplus.application.domain.model.ImageScale;
import com.chatplus.application.domain.response.FileDetailApiResponse;
import com.chatplus.application.domain.vo.file.UpLoadFileVo;
import com.chatplus.application.enumeration.ImgOperateType;
import com.chatplus.application.service.file.FileService;
import com.chatplus.application.service.file.impl.ImgHandler;
import com.chatplus.application.service.provider.FileServiceProvider;
import com.chatplus.application.web.basecontroller.BaseController;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 文件相关控制机器
 */
@RestController
@RequestMapping("/api")
public class FileApiController extends BaseController {

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(FileApiController.class);
    private final FileServiceProvider fileServiceProvider;
    private final ImgHandler imgHandler;
    private final FileDao fileDao;

    public FileApiController(FileServiceProvider fileServiceProvider
            , FileDao fileDao, ImgHandler imgHandler) {
        this.fileServiceProvider = fileServiceProvider;
        this.imgHandler = imgHandler;
        this.fileDao = fileDao;
    }

    @GetMapping("/image/{hashId}")
    @SaIgnore
    public void getImage(@PathVariable String hashId
            , @RequestParam(value = "operateType", required = false) ImgOperateType operateType
            , @RequestParam(value = "width", required = false) Double width
            , @RequestParam(value = "height", required = false) Double height
            , HttpServletResponse response) {
        ImageScale scale = null;
        if (width != null) {
            scale = new ImageScale();
            scale.setWidth(width.intValue());
        }
        if (height != null) {
            if (scale == null) {
                scale = new ImageScale();
            }
            scale.setHeight(height.intValue());
        }
        FileEntity fileEntity = fileDao.selectOne(new LambdaQueryWrapper<FileEntity>().eq(FileEntity::getHashId, hashId), false);
        if (fileEntity == null) {
            throw new BadRequestException("文件不存在");
        }
        FileService fileService = fileServiceProvider.getFileService(fileEntity.getService());
        try (InputStream resultStream = imgHandler.watermarkImage(fileEntity, scale, operateType, null, fileService)) {
            response.setContentLength(resultStream.available());
            response.setContentType(fileEntity.getContentType());
            response.setHeader("Etag", hashId);
            OutputStream os = response.getOutputStream();
            os.write(StreamUtils.copyToByteArray(resultStream));
            //先声明的流后关掉！
            os.flush();
            os.close();
        } catch (IOException e) {
            LOGGER.message("获取图片失败").exception(e).error();
        }
    }

    /**
     * 上传接口
     */
    @PostMapping("/upload")
    public FileDetailApiResponse upload(@RequestParam("file") MultipartFile file) {
        Date date = new Date();
        FileService fileService = fileServiceProvider.getFileService(fileServiceProvider.getActiveFileDriver());
        UpLoadFileVo vo = fileService.uploadFile(file, getUserId());
        vo.setUploadedAt(date);
        if (!Boolean.TRUE.equals(vo.getSuccess())) {
            throw new BadRequestException("图片上传失败，请稍后再试");
        }
        FileDetailApiResponse response = new FileDetailApiResponse();
        response.setUrl(vo.getUrl());
        response.setName(vo.getOriginalName());
        response.setExt(vo.getFileSuffix());
        return response;
    }
    /**
     * 获取文件列表
     */
    @GetMapping("/upload/list")
    public List<FileDetailApiResponse> uploadList() {
        List<FileEntity> fileList = fileDao.selectList(new LambdaQueryWrapper<FileEntity>()
                .eq(FileEntity::getUserId, getUserId()));
        if (CollectionUtils.isEmpty(fileList)) {
            return Collections.emptyList();
        }
        return fileList.stream().map(FileDetailApiResponse::build).toList();
    }

}
